#include <iostream>
#include "Time.h"
#include "Period.h"
#include "Bus.h"
#include "SchoolCard.h"
#include "TimeTable.h"
#include "ctrlcur.h"
#include "TimeTableItem.h"
#include "Date.h"
#include <string>
#include <sstream>
#include <unistd.h>
#include <pthread.h>
#include "data.h"
using namespace std;
int heightRight = 4;
int heightLeft = 4;

int no = 0;
bool thr_run = true;
Bus bus1;


pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* thr_fun1(void* arg) {

    while (thr_run)
    {
        pthread_mutex_lock(&mutex);
        User user = randomUser();

        Card *card1 = nullptr;
        bool success = getCard(&user, card1);

        if(success)
        {
            MOVETO(heightRight, 0);
            card1->TakeBus(&bus1);
            MOVETO(heightLeft, 0);
            delete card1;
        }

        pthread_mutex_unlock(&mutex);
        usleep(20000);
    }
    return nullptr;
}

void Bustest()
{
    SET_BACKGROUND_COLOR(BACKGROUND_BLACK);
    Time now = Time(6, 0);
    Time end = Time(20, 0);
    bus1.startADay();
    pthread_t tid1;
    int err = pthread_create(&tid1, NULL, thr_fun1, NULL);
    if(err != 0)
    {
        cout<<"err create thread!";
        return;
    }
    while(true)
    {

        pthread_mutex_lock(&mutex);
        MOVETO(heightLeft, 0);
        SET_BACKGROUND_COLOR(BACKGROUND_BLACK);
        bus1.getRunningTable()->printCompleteTable();
        now = now + 1;
        cout<<"当前时间：";
        SET_BACKGROUND_COLOR(BACKGROUND_PURPLE);
        cout<<now<<endl;
        SET_BACKGROUND_COLOR(BACKGROUND_BLACK);
        cout<<"编号"<<bus1.getNumOfItem()+1<<" 运行状态:";
        if(bus1.getCurrentState() == run){
            cout<<"途中。剩余大约"<<bus1.getCurrentRunningTableItem().getEndTime()-now<<"分钟到站"<<endl;
        }else{
            cout<<"候车。剩余大约"<<bus1.getCurrentRunningTableItem().getStartTime()-now<<"分钟发车"<<endl;
        }
        bus1.tryRun(now);
        bus1.tryStop(now);
        if(bus1.tryEnd(now)){
            SET_BACKGROUND_COLOR(BACKGROUND_RED);
            cout<<"工作结束，完结撒花"<<endl;
            SET_BACKGROUND_COLOR(BACKGROUND_BLACK);
            break;
        }
        MOVETO(heightRight, 0);
        pthread_mutex_unlock(&mutex);
        usleep(200000);
    }
    thr_run = false;
}
int main(int argc, const char * argv[]) {
    bus1 = getBus();
    Bustest();
    return 0;
}